package com.zebraphp.devtool.httpUtils.cookieJarPersistent.storage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import okhttp3.Cookie;

@SuppressLint("CommitPrefEdits")
public class CookieStoreUtil implements CookieStoreInterfaceStandard {

    private final SharedPreferences sharedPreferences;

    public CookieStoreUtil(Context context) {
        this(context.getSharedPreferences("CookiePersistence", Context.MODE_PRIVATE));
    }

    public CookieStoreUtil(SharedPreferences sharedPreferences) {
        this.sharedPreferences = sharedPreferences;
    }

    //获取 所有的 cookie
    @Override
    public List<Cookie> getAllCookies() {
        List<Cookie> cookies = new ArrayList<>(sharedPreferences.getAll().size());
        
        for (Map.Entry<String, ?> entry : sharedPreferences.getAll().entrySet()) {
            String serializedCookie = (String) entry.getValue();
            Cookie cookie = new SerializableCookie().decode(serializedCookie);
            if (cookie != null) {
                cookies.add(cookie);
            }
        }

        return cookies;
    }

    //保存 所有 所有的cookie
    @Override
    public void saveCookies(Collection<Cookie> cookies) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        for (Cookie cookie : cookies) {
            editor.putString(createCookieKey(cookie), new SerializableCookie().encode(cookie));
        }
        editor.commit();
    }

    @Override
    public void removeCookies (Collection<Cookie> cookies) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        for (Cookie cookie : cookies) {
            editor.remove(createCookieKey(cookie));
        }
        editor.commit();
    }

    private static String createCookieKey(Cookie cookie) {
        return (cookie.secure() ? "https" : "http") + "://" + cookie.domain() + cookie.path() + "|" + cookie.name();
    }

    @Override
    public void clearCookies() {
        sharedPreferences.edit().clear().commit();
    }
}
